/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package AdminServlet;

import Config.Constants;
import DAO.UserDAO;
import DAO.AdminDAO;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import productJAXB.generate.Products;
import sample.utils.FoUtils;

/**
 *
 * @author NganNLK60334
 */
public class AdminController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    public void init() throws ServletException {
        StringWriter productXmlWriter = null;
        try {
            super.init();
            AdminDAO adminDao = new AdminDAO();
            Products productlist = new Products();
            String context = getServletContext().getRealPath("/");
            productlist = adminDao.getAllProducts(context);

            JAXBContext ctx = JAXBContext.newInstance(Products.class);
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);

            productXmlWriter = new StringWriter();
            mar.marshal(productlist, productXmlWriter);
            String productXml = productXmlWriter.toString();
            getServletContext().setAttribute("productXml", productXml);
        } catch (JAXBException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                productXmlWriter.close();
            } catch (IOException ex) {
                Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        AdminDAO adminDAO = new AdminDAO();
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
//        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("USER");
        String role = (String) session.getAttribute("ROLE");
        String action = request.getParameter("btnAction");
        UserDAO userDAO = new UserDAO();

        String url = Constants.manageProductPage;
        try {
            if (action.equals("Login")) {
                url = Constants.manageProductPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (action.equals("manageProduct")) {
                url = Constants.manageProductPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (action.equals("addProducts")) {
                String productName = request.getParameter("txtname");
                int categoryID = 1;
                String price = request.getParameter("txtprice");
                String productImg = request.getParameter("file");
                String option = request.getParameter("option");
                boolean genderProduct = option.equals("male");
                String description = request.getParameter("txtdescription");


                AdminDAO adao = new AdminDAO();
                int resultID = adao.insertProducts(productName, categoryID, price, productImg,
                        genderProduct, description);
                if (resultID != -1) {
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    String productXml = (String) getServletContext().getAttribute("productXml");

                    Document doc = db.parse(new InputSource(new StringReader(productXml)));

                    Element product = doc.createElement("product");

                    Element productID = doc.createElement("productID");
                    productID.setTextContent(resultID + "");
                    product.appendChild(productID);

                    Element productname = doc.createElement("productName");
                    productname.setTextContent(productName);
                    product.appendChild(productname);

                    Element desc = doc.createElement("description");
                    desc.setTextContent(description);
                    product.appendChild(desc);

                    Element pri = doc.createElement("price");
                    pri.setTextContent(price);
                    product.appendChild(pri);

                    Element productImage = doc.createElement("productImg");
                    productImage.setTextContent(productImg);
                    product.appendChild(productImage);

                    Element gender = doc.createElement("genderProduct");
                    gender.setTextContent(genderProduct + "");
                    product.appendChild(gender);

                    Node root = doc.getFirstChild();
                    root.appendChild(product);

                    TransformerFactory tff = TransformerFactory.newInstance();
                    Transformer trans = tff.newTransformer();
                    Source src = new DOMSource(doc);
                    StringWriter sw = new StringWriter();
                    Result result = new StreamResult(sw);
                    trans.setOutputProperty(OutputKeys.INDENT, "no");
                    trans.transform(src, result);
                    productXml = sw.toString();
                    getServletContext().setAttribute("productXml", productXml);
                    request.setAttribute("addSuccess", "Lưu thành công");
                } else {
                    request.setAttribute("addSuccess", "Lưu không thành công");
                }
                String context = getServletContext().getRealPath("/");
                userDAO.MarshallingProducts(context);
                url = Constants.addProductPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (action.equals(
                    "manageFB")) {
                String context = getServletContext().getRealPath("/");
                adminDAO.MarshallingFeedback(context);


                url = Constants.manageFBPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);

            } else if (action.equals(
                    "manageOrder")) {
                String context = getServletContext().getRealPath("/");
                adminDAO.MarshallingOrder(context);
                url = Constants.manageOrderPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (action.equals(
                    "editProduct")) {
                String productName = request.getParameter("productName");
                String price = request.getParameter("price");
                String description = request.getParameter("description");
                String productID = request.getParameter("productID");

                AdminDAO adao = new AdminDAO();
                boolean result = adao.updateProducts(Integer.parseInt(productID), productName, price, description);
                String context = getServletContext().getRealPath("/");
                userDAO.MarshallingProducts(context);
                url = Constants.manageProductPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);

            } else if (action.equals(
                    "addProduct")) {
                url = Constants.addProductPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (action.equals(
                    "deleteProduct")) {
                String productID = request.getParameter("txtID");
                AdminDAO adao = new AdminDAO();
                boolean result = adao.deleteProduct(Integer.parseInt(productID));
                String context = getServletContext().getRealPath("/");
                userDAO.MarshallingProducts(context);
                url = Constants.manageProductPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);


            } else if (action.equals(
                    "deleteFB")) {
                int feedbackID = Integer.parseInt(request.getParameter("txtID"));
                AdminDAO adao = new AdminDAO();
                boolean result = adao.deleteFB(feedbackID);
                String context = getServletContext().getRealPath("/");
                adminDAO.MarshallingFeedback(context);
                url = Constants.manageFBPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            }else if (action.equals("deleteOrder")){
                    String orderID= request.getParameter("txtID");
                AdminDAO adao = new AdminDAO();
                boolean result = adao.deleteOrder(Integer.parseInt(orderID));
                String context = getServletContext().getRealPath("/");
                adminDAO.MarshallingOrder(context);
                url = Constants.manageOrderPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);

                
            }
            else if (action.equals(
                    "logout")) {
                session.getAttribute("USER");
                session.getAttribute("ROLE");
                session.removeAttribute("USER");
                session.removeAttribute("ROLE");
                session.invalidate();
                url = Constants.MainPage;
                RequestDispatcher rd = request.getRequestDispatcher(url);
                rd.forward(request, response);
            } else if (action.equals(
                    "createPDF")) {
                Date date = new Date();
                String webPath = getServletContext().getRealPath("/");
                String productxml = webPath + "WEB-INF/productList.xml";
                String xslFilePath = webPath + "listProductFO.xsl";
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                StreamSource xmlFile = new StreamSource(new File(productxml));
                output = FoUtils.transformToPdf(webPath, xmlFile, xslFilePath);

                response.setContentType("application/pdf");
                byte[] content = output.toByteArray();
                response.setContentLength(content.length);
                // write to output
                response.addHeader("Content-Disposition",
                        "attachment; filename=" + "ListProduct_" + date + ".pdf");
                response.getOutputStream().write(content);
                response.getOutputStream().flush();

            }
        } catch (SAXException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (JAXBException ex) {
            Logger.getLogger(AdminController.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //       out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);


    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";

    }// </editor-fold>
}
